import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';

class EMIAppIosPurchaseManger {
  factory EMIAppIosPurchaseManger() => _instance;

  static final EMIAppIosPurchaseManger _instance =
      EMIAppIosPurchaseManger._internal();

  bool initFinishe = false;
  List<ProductDetails> products = [];
  InAppPurchase? iap;
  PurchaseDetails? pendingData;
  Function(String productID)? buyCallback;

  EMIAppIosPurchaseManger._internal() {
    InAppPurchase.instance.isAvailable().then((available) {
      debugPrint('内购 初始化成功， --- $available');
      if (available) {
        // 初始化成功，可以进行购买操作
        initFinishe = true;
        iap = InAppPurchase.instance;

        addListen();
      }
    });
  }

  addListen() {
    var purchaseUpdated = iap?.purchaseStream;
    purchaseUpdated?.listen((purchases) {
      handlePurchaseUpdates(purchases);
    });
  }

  void handlePurchaseUpdates(List<PurchaseDetails> purchases) {
    debugPrint('内购 购买 回调 ---');
    for (var purchase in purchases) {
      switch (purchase.status) {
        case PurchaseStatus.purchased:
          debugPrint(
              '内购 购买成功， --- ${purchase.productID} ${purchase.purchaseID} ');
          InAppPurchase.instance.completePurchase(purchase);
          if (buyCallback != null && purchase.purchaseID != null) {
            buyCallback!(purchase.purchaseID!);
          }
          break;
        case PurchaseStatus.canceled:
          debugPrint('内购 购买取消 回调 ---');
          InAppPurchase.instance.completePurchase(purchase);
          break;
        case PurchaseStatus.error:
          debugPrint(
              '内购 购买错误 回调 --- ${purchase.verificationData.serverVerificationData}\n source -- ${purchase.productID}');
          debugPrint(
              '内购 购买错误 回调 ---source -- ${purchase.productID} ${purchase.purchaseID}');
          InAppPurchase.instance.completePurchase(purchase);
          break;
        case PurchaseStatus.pending:
          debugPrint('内购 购买进行 回调 ---');
          break;
        default:
      }
    }
  }

  void getProducts(Set<String> dataKIds) async {
    debugPrint('内购 获取产品 -- $dataKIds');
    Set<String> kIds = dataKIds;
    final ProductDetailsResponse response =
        await InAppPurchase.instance.queryProductDetails(kIds);
    if (response.notFoundIDs.isNotEmpty) {
      debugPrint('内购 处理未找到的产品');
    }
    products = response.productDetails;
    debugPrint(
        '内购  找到的产品 --- ${products.length} -- ${products.map((item) => item.id).toList()}');
    // 显示产品列表
  }

  didcsbuy(String id, Function(String purchaseID) buyBack) {
    if (products.isEmpty) return EMILoding.hitLoding('未找到支付产品');
    var data = products.where((data) => data.id == id).first;
    buyProduct(data, buyBack);
  }

  void buyProduct(ProductDetails product, Function(String purchaseID) buyBack) {
    buyCallback = buyBack;
    final PurchaseParam purchaseParam = PurchaseParam(productDetails: product);
    InAppPurchase.instance
        .buyConsumable(purchaseParam: purchaseParam)
        .then((finished) {
      debugPrint('内购 购买进行中22 回调 ---');
    });
  }
}
